"""
agv的定时计划任务
"""
import json
from datetime import datetime, timedelta

from app.core.conf import ST
from app.sche_task import schedulerIns
from app.sio_agv.agv_socket import AGV
from apscheduler.triggers.date import DateTrigger
from loguru import logger
from numpy import number

# from app.sche_task.battery import handle_battery_charge


def register_agv_event():
    # all1
    # try:
    #     schedulerIns.remove_job("all1_info")
    # except Exception as e:
    #     logger.error('暂时没有all1_info的任务，直接添加');
    # schedulerIns.add_job(get_agv1_all1, "interval", seconds=2, args=[], id=ST.AGV1_IP)
    # schedulerIns.add_job(get_agv2_all1, "interval", seconds=2, args=[], id=ST.AGV2_IP)
    # schedulerIns.add_job(get_agv3_all1, "interval", seconds=2, args=[], id=ST.AGV3_IP)
    # schedulerIns.add_job(get_agv4_all1, "interval", seconds=2, args=[], id=ST.AGV4_IP)
    schedulerIns.add_job(get_agv5_all1, "interval", seconds=2, args=[], id=ST.AGV5_IP)


# agv1 all1 info -----------------------------------------------
async def get_agv1_all1():
    agv = AGV.get_agv(ST.AGV1_IP)

    if agv is None:
        change_agv_status(ST.AGV1_IP, False)
        handle_agv_disconnect(ST.AGV1_IP, 10)
        return

    agv.send("status", 1, 1100)
    res = agv.receive("status")
    save_all1_info(ST.AGV1_IP, res)
    change_agv_status(ST.AGV1_IP, True)


# agv2 all1 info -----------------------------------------------
async def get_agv2_all1():
    agv = AGV.get_agv(ST.AGV2_IP)

    if agv is None:
        change_agv_status(ST.AGV2_IP, False)
        handle_agv_disconnect(ST.AGV2_IP, 10)
        return

    agv.send("status", 1, 1100)
    res = agv.receive("status")
    save_all1_info(ST.AGV2_IP, res)
    change_agv_status(ST.AGV2_IP, True)
    # await handle_battery_charge(res,ST.AGV2_IP)


# agv3 all1 info -----------------------------------------------
async def get_agv3_all1():
    agv = AGV.get_agv(ST.AGV3_IP)
    if agv is None:
        change_agv_status(ST.AGV3_IP, False)
        handle_agv_disconnect(ST.AGV3_IP, 10)
        return

    agv.send("status", 1, 1100)
    res = agv.receive("status")
    save_all1_info(ST.AGV3_IP, res)
    change_agv_status(ST.AGV3_IP, True)


# FORK AGV ALL1 INFO -----------------------------------------------
async def get_agv4_all1():
    agv = AGV.get_agv(ST.AGV4_IP)
    if agv is None:
        change_agv_status(ST.AGV4_IP, False)
        handle_agv_disconnect(ST.AGV4_IP, 10)
        return

    agv.send("status", 1, 1100)
    res = agv.receive("status")
    save_all1_info(ST.AGV4_IP, res)
    change_agv_status(ST.AGV4_IP, True)

# agv AGV ALL1 INFO -----------------------------------------------
async def get_agv5_all1():
    agv = AGV.get_agv(ST.AGV5_IP)
    if agv is None:
        change_agv_status(ST.AGV5_IP, False)
        handle_agv_disconnect(ST.AGV5_IP, 10)
        return

    agv.send("status", 1, 1100)
    res = agv.receive("status")
    save_all1_info(ST.AGV5_IP, res)
    change_agv_status(ST.AGV5_IP, True)

# ================================================================================================================================================================================================


def change_agv_status(ip, status):
    """改变AGV的状态
    Args:
        ip (_type_): _description_
        status (_type_): _description_
    """
    with open(ST.AGV_STATUS_PATH, "r", encoding="utf-8") as f:
        content = json.load(f)
    content[ip]["status"] = status
    # 将修改后的字典重新编码为JSON字符串
    json_str = json.dumps(content)
    # 将JSON字符串写入文件
    with open(ST.AGV_STATUS_PATH, "w", encoding="utf-8") as f:
        f.write(json_str)


def save_all1_info(ip, all1):
    """将all1 info的信息存储起来

    Args:
        all1 (_type_): _description_
        ip (_type_): _description_
    """
    json_str = json.dumps(all1)
    with open(ST.get_all1_info_path(ip), "w", encoding="utf-8") as f:
        f.writelines(json_str + "\n")


def handle_agv_disconnect(ip: str, min: int):
    """处理AGV断开连接，min分钟后重新连接

    Args:
        ip (str): _description_
        min (int): _description_
    """
    logger.warning(f"{ip},断开连接")
    schedulerIns.pause_job(ip)
    run_date = datetime.now() + timedelta(minutes=min)
    schedulerIns.add_job(schedulerIns.resume_job, DateTrigger(run_date=run_date), args=[ST.AGV3_IP], id=f"resume_{ip}")
    return
